package com.zkw.netty;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerAdapter;
import io.netty.channel.ChannelHandlerContext;
import io.netty.util.AttributeKey;

/**
 * Created by Administrator on 2016/4/30 0030.
 */
public class DiscardClientHandler extends ChannelHandlerAdapter {
    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
//        String req = (String)ctx.channel().attr(AttributeKey.valueOf(CommonConstants.Attribute_key)).get();
//        System.out.println("请求数据为： "+req);
//        ByteBuf byteBuf = ctx.alloc().buffer().writeBytes(req.getBytes("UTF-8"));
//        ctx.writeAndFlush(byteBuf);
    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        ByteBuf byteBuf = (ByteBuf)msg;
        StringBuilder builder = new StringBuilder();
        System.out.print("client recv: ");
        while (byteBuf.isReadable()){
            builder.append((char) byteBuf.readByte());
            System.out.flush();
        }
        //将从服务端传回的数据放入到channel中,并可以在DiscardClient中获取
        ctx.channel().attr(AttributeKey.valueOf(CommonConstants.Attribute_key)).set(builder.toString());
        ctx.channel().close();
        ctx.close();
        byteBuf.clear();
    }
}
